package com.sky.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.ShoppingCartDTO;
import com.sky.dto.mapper.ShoppingCartDTOMapper;
import com.sky.entity.Dish;
import com.sky.entity.Setmeal;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddCartFailedException;
import com.sky.exception.DeletionCartFailedException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.exception.UpdateCartFailedException;
import com.sky.mapper.DishMapper;
import com.sky.mapper.SetmealMapper;
import com.sky.service.ShoppingCartService;
import com.sky.mapper.ShoppingCartMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * @author luo20
 * @description 针对表【shopping_cart(购物车)】的数据库操作Service实现
 * @createDate 2025-07-21 23:06:57
 */
@Service
@Slf4j
public class ShoppingCartServiceImpl extends ServiceImpl<ShoppingCartMapper, ShoppingCart>
        implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private ShoppingCartDTOMapper shoppingCartDTOMapper;
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private SetmealMapper setmealMapper;

    @Override
    public void addShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        // dto转entity
        ShoppingCart shoppingCart = shoppingCartDTOMapper.toShoppingCart(shoppingCartDTO);
        // 获取用户id
        Long userId = BaseContext.getCurrentId();
        // 设置用户id
        shoppingCart.setUserId(userId);
        // 判断当前加入到购物车的商品是否在购物车中
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        // 如果已经存在，则数量加1
        if (CollectionUtils.isNotEmpty(shoppingCartList)) {
            ShoppingCart cart = shoppingCartList.get(0);
            cart.setNumber(cart.getNumber() + 1);

            Integer updateCartNumberById = shoppingCartMapper.updateCartNumberById(cart);
            // 判断如果更新失败，则抛出业务异常
            if (updateCartNumberById <= 0) {
                throw new UpdateCartFailedException(MessageConstant.UPDATE_CART_NUMBER_FAILED);
            }
        } else {
            // 如果不存在，则需要插入一条购物车数据

            // 判断本次添加到购物车的是菜品还是套餐
            Long dishId = shoppingCartDTO.getDishId();
            if (dishId != null) {
                // 本次添加到购物车的是菜品
                Dish dish = dishMapper.selectById(dishId);
                shoppingCart.setName(dish.getName());
                shoppingCart.setImage(dish.getImage());
                shoppingCart.setAmount(dish.getPrice());
            } else {
                // 本次添加到购物车是套餐
                Long setmealId = shoppingCartDTO.getSetmealId();
                Setmeal setmeal = setmealMapper.selectById(setmealId);
                shoppingCart.setName(setmeal.getName());
                shoppingCart.setImage(setmeal.getImage());
                shoppingCart.setAmount(setmeal.getPrice());
            }
            shoppingCart.setNumber(1);
            shoppingCart.setCreateTime(LocalDateTime.now());
            // 添加到购物车
            Integer insertResult = shoppingCartMapper.insertCart(shoppingCart);
            if (insertResult <= 0) {
                throw new AddCartFailedException(MessageConstant.ADD_SHOPPING_CART_FAILED);
            }
        }


    }

    @Override
    public List<ShoppingCart> showShoppingCart() {
        // 获取userId
        Long userId = BaseContext.getCurrentId();
        return shoppingCartMapper.list(new ShoppingCart().setUserId(userId));
    }

    @Override
    public void subShoppingCart(ShoppingCartDTO shoppingCartDTO) {
        // dto转entity
        ShoppingCart shoppingCart = shoppingCartDTOMapper.toShoppingCart(shoppingCartDTO);
        // 设置userId
        shoppingCart.setUserId(BaseContext.getCurrentId());
        // 根据商品查询购物车中商品的数量是否大于1，大于1，则数量减1
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (CollectionUtils.isNotEmpty(shoppingCartList)) {
            ShoppingCart cart = shoppingCartList.get(0);
            cart.setNumber(cart.getNumber() - 1);
            if (cart.getNumber() == 0) {
                // 如果数量小于1，则删除商品
                Integer delCartResult = shoppingCartMapper.delCart(shoppingCart);
                if (delCartResult <= 0) {
                    throw new DeletionCartFailedException(MessageConstant.CART_REMOVE_FAILED);
                }
            } else {
                // 如果数量大于0，则更新商品数量
                Integer updateCartNumberById = shoppingCartMapper.updateCartNumberById(cart);
                // 判断如果更新失败，则抛出业务异常
                if (updateCartNumberById <= 0) {
                    throw new UpdateCartFailedException(MessageConstant.UPDATE_CART_NUMBER_FAILED);
                }
            }
        }
    }

    @Override
    public void cleanCart() {
        // 创建shoppingCart对象
        ShoppingCart shoppingCart = new ShoppingCart();
        // 设置userId
        shoppingCart.setUserId(BaseContext.getCurrentId());
        // 判断购物车是否为空，为空说明已经清空过了
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
        if (CollectionUtils.isNotEmpty(shoppingCartList)){
            // 不为空，根据用户id清空购物车
            Integer clearCartResult = shoppingCartMapper.delCart(shoppingCart);
            if (clearCartResult <= 0) {
                throw new DeletionCartFailedException(MessageConstant.CART_CLEAN_FAILED);
            }
        }

    }


}




